<template>
  <div class="weapon-audit">
    <el-card class="control-card">
      <div class="header-controls">
        <div class="info">
          <h3>
            武器装备数据审核
            <el-text type="info" size="small" style="margin-left: 20px; font-weight: normal;">
              待审核: {{ statistics.pending }} 条
            </el-text>
          </h3>
        </div>
        <div class="actions">
          <el-button @click="() => loadNextRecord(true)">跳过</el-button>
          <el-button 
            type="warning" 
            @click="handleReprocess" 
            :loading="reprocessing"
          >
            重新解析
          </el-button>
          <el-button type="danger" @click="handleReject" :disabled="!currentRecord" :loading="submitting">
            驳回
          </el-button>
          <el-button type="success" @click="handleApprove" :disabled="!currentRecord" :loading="submitting">
            通过
          </el-button>
        </div>
      </div>
    </el-card>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="12" animated />
    </div>

    <el-empty v-else-if="!currentRecord" description="暂无待审核记录" :image-size="200" />

    <div v-else class="audit-content">
      <!-- 左侧：原始数据 -->
      <el-card class="left-panel">
        <template #header>
          <div class="card-header">
            <span>原始数据</span>
            <el-tag type="info" size="small">ID: {{ currentRecord.rawRecord.id }}</el-tag>
          </div>
        </template>

        <div class="original-info">
          <h3>{{ currentRecord.rawRecord.name }}</h3>
          <p class="data-source" v-if="currentRecord.rawRecord.data_source">
            数据源: {{ currentRecord.rawRecord.data_source }}
          </p>
        </div>

        <el-divider content-position="left">装备介绍</el-divider>
        <div class="description-box markdown-content" v-html="renderMarkdown(currentRecord.rawRecord.description)"></div>
      </el-card>

      <!-- 右侧：处理后的可编辑数据 -->
      <el-card class="right-panel">
        <template #header>
          <div class="card-header">
            <span>处理后数据（可编辑）</span>
            <el-button text type="primary" size="small" @click="resetForm">
              重置
            </el-button>
          </div>
        </template>

        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-form
              ref="basicFormRef"
              :model="editForm.basicInfo"
              label-width="120px"
              size="small"
              class="edit-form"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="中文名称">
                    <el-input v-model="editForm.basicInfo.chinese_name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="英文名称">
                    <el-input v-model="editForm.basicInfo.english_name" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="原产国">
                    <el-input v-model="editForm.basicInfo.origin_country" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="装备分类">
                    <el-input v-model="editForm.basicInfo.category" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="承包商">
                    <el-input v-model="editForm.basicInfo.contractor" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="服役时间">
                    <el-input v-model="editForm.basicInfo.service_time" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="中文简介">
                <el-input
                  v-model="editForm.basicInfo.chinese_intro"
                  type="textarea"
                  :rows="4"
                />
              </el-form-item>

              <el-form-item label="英文简介">
                <el-input
                  v-model="editForm.basicInfo.english_intro"
                  type="textarea"
                  :rows="4"
                />
              </el-form-item>

              <el-form-item label="研制背景">
                <el-input
                  v-model="editForm.basicInfo.development_background"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="建造沿革">
                <el-input
                  v-model="editForm.basicInfo.construction_history"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="服役历程">
                <el-input
                  v-model="editForm.basicInfo.service_history"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="结构特征">
                <el-input
                  v-model="editForm.basicInfo.structural_features"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="配备装备">
                <el-input
                  v-model="editForm.basicInfo.equipment"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="动力系统">
                <el-input
                  v-model="editForm.basicInfo.power_system"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="状态">
                    <el-input v-model="editForm.basicInfo.status" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="数据来源">
                    <el-input v-model="editForm.basicInfo.data_source" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>

          <!-- 战技指标 -->
          <el-tab-pane label="战技指标" name="specs">
            <div class="specs-section">
              <el-button 
                type="primary" 
                size="small" 
                @click="addTopLevelSpec"
                style="margin-bottom: 15px"
              >
                <el-icon><Plus /></el-icon>
                添加顶级节点
              </el-button>
              
              <el-table
                :data="editForm.specifications"
                row-key="id"
                border
                default-expand-all
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                :indent="20"
                style="width: 100%"
                class="tree-table-specs"
              >
                <el-table-column label="" width="80" align="center" />
                
                <el-table-column label="名称/指标" min-width="250">
                  <template #default="{ row }">
                    <div class="spec-name-cell">
                      <el-input 
                        v-model="row.indicator_chinese" 
                        size="small" 
                        :placeholder="row.node_type === 'category' ? '分类名称' : '指标中文名'"
                        :class="row.node_type === 'category' ? 'category-input' : 'indicator-input'"
                      />
                    </div>
                  </template>
                </el-table-column>
                
                <el-table-column label="英文名称" min-width="180">
                  <template #default="{ row }">
                    <el-input 
                      v-if="row.node_type === 'indicator'"
                      v-model="row.indicator_english" 
                      size="small" 
                      placeholder="指标英文名"
                    />
                    <span v-else class="text-placeholder">-</span>
                  </template>
                </el-table-column>
                
                <el-table-column label="指标值" min-width="180">
                  <template #default="{ row }">
                    <el-input 
                      v-if="row.node_type === 'indicator'"
                      v-model="row.indicator_value" 
                      size="small" 
                      placeholder="指标值"
                    />
                    <span v-else class="text-placeholder">-</span>
                  </template>
                </el-table-column>
                
                <el-table-column label="操作" width="180" align="center">
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="addChildSpec(row)"
                      title="添加子节点"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-button>
                    <el-button
                      type="warning"
                      size="small"
                      text
                      @click="toggleNodeType(row)"
                      title="切换类型"
                    >
                      <el-icon><Refresh /></el-icon>
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      text
                      @click="removeSpec(row)"
                      title="删除节点"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 使用用户 -->
          <el-tab-pane label="使用用户" name="users">
            <div class="users-section">
              <el-button 
                type="primary" 
                size="small" 
                @click="addUser"
                style="margin-bottom: 15px"
              >
                添加用户
              </el-button>
              
              <el-table
                :data="editForm.users"
                border
                style="width: 100%"
              >
                <el-table-column label="国家" width="120">
                  <template #default="{ row }">
                    <el-input v-model="row.country" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="装备变体" min-width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.variant" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="运营商中文" min-width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.operator_chinese" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="运营商英文" min-width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.operator_english" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="订单数量" width="120">
                  <template #default="{ row }">
                    <el-input v-model="row.order_quantity" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center">
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      size="small"
                      text
                      @click="removeUser($index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 审核意见 -->
        <div class="comment-section">
          <el-divider content-position="left">审核意见</el-divider>
          <el-input
            v-model="auditComment"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见（选填）"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh } from '@element-plus/icons-vue'
import { weaponApi } from '@/api/weapon'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const loading = ref(false)
const submitting = ref(false)
const reprocessing = ref(false)
const activeTab = ref('basic')
const currentRecord = ref(null)
const auditComment = ref('')
const pendingList = ref([])

const statistics = reactive({
  pending: 0
})

const editForm = reactive({
  basicInfo: {},
  specifications: [],
  users: []
})

// 加载待审核列表
const loadPendingList = async () => {
  try {
    const result = await weaponApi.getPendingAudit({ page: 1, pageSize: 100 })
    pendingList.value = result.data || []
    statistics.pending = result.total || 0
  } catch (error) {
    console.error('加载待审核列表失败:', error)
  }
}

// 加载下一条记录
const loadNextRecord = async (skip = false) => {
  loading.value = true
  try {
    // 如果跳过当前记录，从列表中移除
    if (skip && currentRecord.value) {
      const currentId = currentRecord.value.rawRecord.id
      pendingList.value = pendingList.value.filter(item => item.id !== currentId)
      statistics.pending = Math.max(0, statistics.pending - 1)
    }

    // 获取下一条
    if (pendingList.value.length === 0) {
      await loadPendingList()
    }

    if (pendingList.value.length === 0) {
      currentRecord.value = null
      ElMessage.info('没有更多待审核记录')
      return
    }

    const nextId = pendingList.value[0].id
    const result = await weaponApi.getDetail(nextId)
    
    if (result.success) {
      currentRecord.value = result
      resetForm()
    }
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (!currentRecord.value) return

  // 基本信息
  editForm.basicInfo = { ...currentRecord.value.basicInfo } || {}

  // 战技指标 - 确保每个节点都有ID
  const specs = JSON.parse(JSON.stringify(currentRecord.value.specifications || []))
  editForm.specifications = ensureSpecIds(specs)

  // 使用用户
  editForm.users = JSON.parse(JSON.stringify(currentRecord.value.users || []))

  auditComment.value = ''
  activeTab.value = 'basic'
}

// 生成唯一ID
let specIdCounter = Date.now()
const generateSpecId = () => {
  return `spec_${specIdCounter++}`
}

// 为树形数据添加ID（如果没有）
const ensureSpecIds = (specs) => {
  if (!specs || !Array.isArray(specs)) return []
  
  return specs.map(spec => {
    const newSpec = { ...spec }
    if (!newSpec.id) {
      newSpec.id = generateSpecId()
    }
    if (newSpec.children && newSpec.children.length > 0) {
      newSpec.children = ensureSpecIds(newSpec.children)
    }
    return newSpec
  })
}

// 添加顶级战技指标节点
const addTopLevelSpec = () => {
  editForm.specifications.push({
    id: generateSpecId(),
    node_type: 'category',
    indicator_chinese: '',
    indicator_english: '',
    indicator_value: '',
    children: []
  })
}

// 添加子节点
const addChildSpec = (parentNode) => {
  if (!parentNode.children) {
    parentNode.children = []
  }
  
  parentNode.children.push({
    id: generateSpecId(),
    node_type: 'indicator',
    indicator_chinese: '',
    indicator_english: '',
    indicator_value: '',
    children: []
  })
}

// 递归查找并删除节点
const findAndRemoveSpec = (specs, targetNode) => {
  for (let i = 0; i < specs.length; i++) {
    if (specs[i].id === targetNode.id) {
      specs.splice(i, 1)
      return true
    }
    if (specs[i].children && specs[i].children.length > 0) {
      if (findAndRemoveSpec(specs[i].children, targetNode)) {
        // 如果子节点为空，删除children属性
        if (specs[i].children.length === 0) {
          delete specs[i].children
        }
        return true
      }
    }
  }
  return false
}

// 删除战技指标节点
const removeSpec = (node) => {
  ElMessageBox.confirm('确定删除此节点及其所有子节点吗？', '确认删除', {
    type: 'warning'
  }).then(() => {
    findAndRemoveSpec(editForm.specifications, node)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 切换节点类型
const toggleNodeType = (node) => {
  if (node.node_type === 'category') {
    node.node_type = 'indicator'
    ElMessage.success('已切换为指标节点')
  } else {
    node.node_type = 'category'
    ElMessage.success('已切换为分类节点')
  }
}

// 添加使用用户
const addUser = () => {
  editForm.users.push({
    country: '',
    variant: '',
    operator_chinese: '',
    operator_english: '',
    operator_intro: '',
    order_quantity: ''
  })
}

// 删除使用用户
const removeUser = (index) => {
  editForm.users.splice(index, 1)
}

// 通过审核
const handleApprove = async () => {
  try {
    await ElMessageBox.confirm('确定通过审核吗？', '确认操作', {
      type: 'success'
    })
  } catch {
    return
  }

  submitting.value = true

  try {
    const result = await weaponApi.submitAudit({
      rawWeaponId: currentRecord.value.rawRecord.id,
      auditStatus: 'approved',
      comment: auditComment.value,
      updatedData: {
        basicInfo: editForm.basicInfo,
        specifications: editForm.specifications,
        users: editForm.users
      }
    })

    if (result.success) {
      ElMessage.success('审核通过')
      await loadNextRecord(true)
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 驳回审核
const handleReject = async () => {
  if (!auditComment.value.trim()) {
    ElMessage.warning('驳回时必须填写审核意见')
    return
  }

  try {
    await ElMessageBox.confirm('确定驳回吗？', '确认操作', {
      type: 'warning'
    })
  } catch {
    return
  }

  submitting.value = true

  try {
    const result = await weaponApi.submitAudit({
      rawWeaponId: currentRecord.value.rawRecord.id,
      auditStatus: 'rejected',
      comment: auditComment.value
    })

    if (result.success) {
      ElMessage.success('已驳回')
      await loadNextRecord(true)
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 重新解析
const handleReprocess = async () => {
  try {
    await ElMessageBox.confirm('确定重新解析这条记录吗？这将删除现有的处理结果并重新调用AI进行解析。', '确认操作', {
      type: 'warning'
    })
  } catch {
    return
  }

  reprocessing.value = true

  try {
    const result = await weaponApi.reprocessRecord(currentRecord.value.rawRecord.id)

    if (result.success) {
      ElMessage.success('重新解析成功')
      // 重新加载当前记录
      const detailResult = await weaponApi.getDetail(currentRecord.value.rawRecord.id)
      if (detailResult.success) {
        currentRecord.value = detailResult
        resetForm()
      }
    } else {
      ElMessage.error(result.message || '重新解析失败')
    }
  } catch (error) {
    ElMessage.error('重新解析失败: ' + error.message)
  } finally {
    reprocessing.value = false
  }
}

// 渲染 Markdown
const renderMarkdown = (markdown) => {
  if (!markdown) return '<p class="empty-text">暂无内容</p>'
  
  try {
    marked.setOptions({
      breaks: true,
      gfm: true
    })
    
    const html = marked.parse(markdown)
    return DOMPurify.sanitize(html)
  } catch (error) {
    console.error('Markdown 渲染失败:', error)
    return '<p class="error-text">Markdown 格式错误</p>'
  }
}

onMounted(() => {
  loadNextRecord()
})
</script>

<style lang="scss" scoped>
.weapon-audit {
  .text-placeholder {
    color: #c0c4cc;
    font-size: 12px;
  }

  // 树形表格样式增强
  .tree-table-specs {
    :deep(.el-table__body-wrapper) {
      .el-table__row {
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }

    // 第一列展开按钮列
    :deep(.el-table__body) {
      .el-table__row {
        .el-table__cell:first-child {
          .cell {
            display: flex;
            align-items: center;
            padding: 0;
            padding-left: 0 !important;
          }
        }
      }
    }

    // 根据层级设置展开按钮左侧空白
    :deep(.el-table__indent) {
      display: inline-block;
      width: 20px;
      height: 1px;
    }

    // 展开按钮样式
    :deep(.el-table__expand-icon) {
      font-size: 14px;
      color: #409eff;
      margin-left: 5px;
      
      &:hover {
        color: #66b1ff;
      }
    }

    // 层级视觉辅助线
    :deep(.el-table__placeholder) {
      display: inline-block;
      width: 20px;
      height: 100%;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        left: 10px;
        top: 0;
        bottom: 0;
        width: 1px;
        background-color: #dcdfe6;
      }
    }

    .spec-name-cell {
      .category-input {
        :deep(.el-input__wrapper) {
          background-color: #f0f9ff;
          border-left: 3px solid #409eff;
        }
      }

      .indicator-input {
        :deep(.el-input__wrapper) {
          background-color: #f0f9ff;
          border-left: 3px solid #67c23a;
        }
      }
    }
  }

  .control-card {
    margin-bottom: 20px;
  }

  .header-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 18px;
    }

    .actions {
      display: flex;
      gap: 10px;
    }
  }

  .loading-container {
    padding: 20px;
  }

  .audit-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;

    .left-panel,
    .right-panel {
      height: calc(100vh - 190px);
      overflow-y: auto;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
    }
  }

  .original-info {
    h3 {
      margin: 0 0 10px;
      font-size: 20px;
      font-weight: 600;
    }

    .data-source {
      color: #909399;
      font-size: 14px;
    }
  }

  .description-box {
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    max-height: 600px;
    overflow-y: auto;
  }

  .markdown-content {
    :deep(h1) { font-size: 24px; margin: 20px 0 15px; padding-bottom: 10px; border-bottom: 1px solid #eee; }
    :deep(h2) { font-size: 20px; margin: 18px 0 12px; padding-bottom: 8px; border-bottom: 1px solid #f0f0f0; }
    :deep(h3) { font-size: 18px; margin: 16px 0 10px; }
    :deep(p) { margin: 8px 0; line-height: 1.8; }
    :deep(ul), :deep(ol) { margin: 10px 0; padding-left: 25px; }
    :deep(li) { margin: 5px 0; line-height: 1.6; }
    :deep(table) { width: 100%; margin: 15px 0; border-collapse: collapse; }
    :deep(th), :deep(td) { padding: 8px 12px; border: 1px solid #ddd; }
    :deep(th) { background-color: #f4f4f5; font-weight: bold; }
  }

  .edit-form {
    :deep(.el-form-item) {
      margin-bottom: 18px;
    }
  }

  .comment-section {
    margin-top: 20px;
  }

  .specs-section,
  .users-section {
    padding: 10px 0;
  }
}
</style>

